﻿/* Copyright (C) 2015 Mustansir Husain (mustansir.husain@live.com) - All Rights Reserved
 * You may use, distribute and modify this code under the
 * terms of the GPL v3 license.
 *
 * Visit https://simplelogging.codeplex.com/license for code use, distribution and modification terms and conditions.
 */
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using System.Diagnostics;
using System.IO;

namespace LoggingLibrary
{
    public static class Logger
    {
        public enum LogRepository
        {
            EventLog = 0,
            FileLog
        }

        public static void WriteToFileLog(string logMessage, string logPath)
        {
            TextFormatter briefFormatter = new TextFormatter();

            var flatFileTraceListener = new FlatFileTraceListener(logPath,
                "----------------------------------------", 
                "----------------------------------------",
                briefFormatter);

            var config = new LoggingConfiguration();
            config.AddLogSource("LogFile", SourceLevels.All, true)
                .AddTraceListener(flatFileTraceListener);

            LogWriter defaultWriter = new LogWriter(config);

            if (defaultWriter.IsLoggingEnabled())
            {
                try
                {
                    if (!File.Exists(logPath))
                    {
                        File.Create(logPath).Dispose();
                    }
                    defaultWriter.Write(logMessage);
                }
                catch (IOException)
                {
                    throw;
                }
            }
        }

        public static void WriteToEventLog(string logMessage, string logCategory, string logSource = "EntLib Logging")
        {
            TextFormatter briefFormatter = new TextFormatter();

            var eventLog = new EventLog("Application", ".", logSource);
            var eventLogTraceListener = new FormattedEventLogTraceListener(eventLog);

            var config = new LoggingConfiguration();
            config.AddLogSource(logCategory, SourceLevels.All, true)
                .AddTraceListener(eventLogTraceListener);

            LogWriter defaultWriter = new LogWriter(config);
            defaultWriter.Write(logMessage);
        }
    }
}
